// 语音识别接口

package misc

import (
	"context"
	"dhfshop/controllers/base"
	"dhfshop/models/proto"
	"encoding/base64"
	"github.com/astaxie/beego"
	"github.com/satori/go.uuid"
	"github.com/smallnest/rpcx/client"
	"io/ioutil"
	"strconv"
	"time"
)

type SpeechController struct {
	base.BaseController
}

func (this *SpeechController) AddSpeechTask() {
	//companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	file, _, err := this.GetFile("wxfile")
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	keyId := uuid.NewV4().String()
	bytesContent, err := ioutil.ReadAll(file)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	file.Close()
	attach := this.GetString("attach")
	var language int = 0
	if tmppara, err := this.GetInt("language"); err == nil {
		language = tmppara
	}
	rpcAddr := beego.AppConfig.String("RpcAddr")
	d := client.NewPeer2PeerDiscovery("tcp@"+rpcAddr, "")
	xclient := client.NewXClient("SpeechApi", client.Failtry, client.RandomSelect, d, client.DefaultOption)
	defer xclient.Close()
	encodeString := base64.StdEncoding.EncodeToString(bytesContent)
	args := &proto.Args{
		UserId:      strconv.FormatInt(curUserId, 10),
		Uuid:        keyId,
		Attach:      attach,
		AudioBase64: encodeString,
		Language:    language,
	}
	reply := &proto.Reply{}
	_, err = xclient.Go(context.Background(), "Recognition", args, reply, nil)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		Uuid    string    `json:"uuid"`
		Created time.Time `json:"created"`
	}{Uuid: keyId, Created: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *SpeechController) GetSpeechTaskResult() {
	//companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	this.Data["json"] = "等测试完成后，后续支持"
	this.ServeJSON()
}
